package com.cr.crandroid.ui.person.kefu;


import android.content.Context;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.cr.crandroid.R;
import com.cr.crandroid.utils.CommonConstant;
import com.cr.crandroid.utils.Msg;
import com.cr.crandroid.utils.MsgAdapter;
import com.cr.crandroid.utils.OkHttpManager;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class KefuFragment extends AppCompatActivity {
    List<Msg> list = new ArrayList<>();             // 存储消息
    private final static int READ_TIMEOUT = 100;
    private final static int CONNECT_TIMEOUT = 60;
    private final static int WRITE_TIMEOUT = 60;   RecyclerView recyclerView;
    Toolbar toolbar;
    MsgAdapter msgAdapter;
    Context context = KefuFragment.this;
    EditText msg_say;
    Button tpsb;
    Button send;
    LinearLayout linearLayout;
    int lastx = 0;
    int lasty = 0;
    String finalResult = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_kefu);
        recyclerView = findViewById(R.id.msg_list);
        toolbar = findViewById(R.id.msg_toolbar);
        setSupportActionBar(toolbar);
        msg_say = findViewById(R.id.msg_say);
        tpsb = findViewById(R.id.msg_tpsb);
        send = findViewById(R.id.msg_send);
        linearLayout = findViewById(R.id.linear);
        initData();

        // 判断是否有网
        if(isOpenNetwork()){
//            Toast.makeText(KefuFragment.this,"当前处于联网状态",Toast.LENGTH_SHORT).show();
            initLWView();
            initStatusBar();
        }
    }

    // 处理当设备的API高时，出现页面不适配的情况
    private void initStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }

    // 初始化数据
    private void initData() {
        Msg msg = new Msg("你好，我是紧急助手，有什么问题？", Msg.type_received);
        list.add(msg);
    }

    // 初始化页面
    private void initLWView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        msgAdapter = new MsgAdapter(list, context);
        recyclerView.setAdapter(msgAdapter);
        // 点击后退，则该页面完成，返回上一个页面
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        send.getLayoutParams().width = tpsb.getLayoutParams().width;
        // 处理提交图片
        sendImage();
        // 提问处理
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 校验文本不能为空
                if (msg_say.getEditableText().length() >= 1) {
                    String content = msg_say.getText().toString();
                    if (!"".equals(content)) {
                        // 添加问题
                        Msg msg = new Msg(content, Msg.type_sent);
                        list.add(msg);
                        // 访问大模型，获取结果
                        kefu(content);
                        msgAdapter.notifyItemInserted(list.size() - 1);
                        recyclerView.scrollToPosition(list.size() - 1);
                        msg_say.setText("");
                    }
                } else {
                    Toast.makeText(context, "请输入你想说的话", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    // 访问大模型，实现客服功能
    private void kefu(String msg) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Map<String, String> map = new HashMap<>();
                map.put("message", msg);
                OkHttpManager.get(CommonConstant.URL + "/znwd/kefu", map, new Callback() {
                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        try {
                            String res = response.body().string();
                            JsonObject result = JsonParser.parseString(res).getAsJsonObject();
                            if (Integer.parseInt(String.valueOf(result.get("code"))) != CommonConstant.ERROR) {
                                if (result.get("result") != null) {
                                    finalResult = result.get("result").getAsString();
                                }
                            }
                            if(finalResult!=null && !finalResult.equals("")){
                                // 添加结果
                                Msg msg1 = new Msg(finalResult, Msg.type_received);
                                list.add(msg1);
                                // 当数据多时，自动滚到最下
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        recyclerView.scrollToPosition(list.size() - 1);
                                    }
                                });
                            }
                        } catch (Exception e) {
                            finalResult = "客服处理失败，请重新提问";
                        }
                    }
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        finalResult = "客服处理失败，请重新提问";
                    }
                });
            }
        }).start();
    }

    private void sendImage(){
        send.setBackgroundResource(R.drawable.buttonbackground);
        send.setText("发送");
        send.getLayoutParams().height = tpsb.getLayoutParams().height;
        send.getLayoutParams().width = tpsb.getLayoutParams().width + 10;
        send.setTextColor(context.getResources().getColor(R.color.white));
    }

    // 在Activity销毁前执行一些操作
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 对网络连接状态进行判断
     */
    private boolean isOpenNetwork() {
        ConnectivityManager connManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        if(connManager.getActiveNetworkInfo() != null) {
            return connManager.getActiveNetworkInfo().isAvailable();
        }

        return false;
    }
}